import React, { useEffect, useState, useMemo, useRef, forwardRef, useReducer } from 'react';
import {
  Switch,
  Route,
  withRouter,
  useHistory,
  Link,
} from "react-router-dom";
import classNames from 'classnames';
import { RawBtn } from '../components/Btn';
import { StandardBleConnector } from '../StandardBleDemo/components/StandardBleConnector';
import { InputUserPage } from './InputUserPage';
import { CklsPage } from './CklsPage';
import { SjfxPage } from './SjfxPage';
import { DeviceDetail } from './DeviceDetail';
import { DbfxPage } from './DbfxPage';
import { Version } from './Version';
import sdk from 'qcloud-iotexplorer-h5-panel-sdk';
import { useDeviceData } from '../hooks/useDeviceData';
import PubSub from 'pubsub-js' //引入
import moment from 'moment';
import './Jkcard.less';
import { Toast } from 'antd-mobile';
import { IMGURL, APIURL, APPID, APPSECRET, forunit, matAge } from '../utils/common';
import { md5 } from "./md5.js"
const thirdUserNo = "para_user1"
const CTYPE = 1
// 当前时间
const current_time = (new Date()).valueOf()
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
let myuserInfo = sdk.userInfo
// 目标体重
const MBWEIGHT = 68.00 
const resageRange = ["<实际", ">=实际"]
const resbmrRange = ["不⾜", "标准"]
const resbmiWHORange = ["偏瘦", "健康", "偏胖", "肥胖"]
const resFatRange1 = ["偏瘦", "健康", "警戒", "轻度肥胖", "重度肥胖"]
const resweightRange = ["不⾜", "过轻", "标准", "过重", "肥胖"]
const resMuscleRange = ["不⾜", "标准", "优"]
const resMuscleKg = ["偏低", "正常", "偏⾼"]
const resWaterRange = ["缺失", "标准", "优"]
const resBoneRange = ["偏低", "正常", "优"]
const resFatRange = ["正常", "偏⾼", "严重偏⾼"]
const resbodyShape = ["无", "隐性胖", "偏胖型", "运动型偏胖", "缺乏锻炼型", "标准型", "标准运动型", "偏瘦型", "偏瘦运动型", "运动健美型"]
const resNutrition = ["无", "严重营养不良", "中度营养不良", "营养不良", "标准", "营养过剩", "营养严重过剩"]
const resobesity = ["较轻", "正常", "轻度肥胖", "中度肥胖", "重度肥胖", "极度肥胖"]

const listbmrRange = [1642.4]
const listbmiWHORange = [0, 18.5, 24, 30]
const listFatRange1 = [7.37, 15.47, 19.15]
const listweightRange = [61.739998,75.46]
const listMuscleRange = [49.4, 59.4]
const listMuscleKg = [10, 21, 26]
const listWaterRange = [55, 65]
const listBoneRange = [0,10]
const listFatRange = [7.37, 15.47, 19.15]
const listbodyShape =[18.5, 24.9, 29.9, 35, 40]
const listNutrition = [18.5, 24.9, 29.9, 35, 40]
const listobesity = [18.5, 24.9, 29.9, 35, 40]

let LayoutRouter = () => (
  <div>
    <Switch>
      <Route path="/Home" exact><Home /></Route>
      <Route path="/CklsPage" exact><CklsPage /></Route>
      <Route path="/PanelPage" exact><PanelPage /></Route>
      <Route path="/InputUserPage" exact ><InputUserPage isinput={true} /></Route>
      <Route path="/DbfxPage" exact><DbfxPage /></Route>
      <Route path="/SjfxPage" exact><SjfxPage /></Route>
      <Route path="/DeviceDetail" exact><DeviceDetail /></Route>
      <Route path="/"><Home /></Route>
    </Switch>
  </div>
);
export function Jkcard(props) {
  const [sdkReady, setSdkReady] = useState(false);
  useEffect(() => {
    h5PanelSdk.sdkReady().then(() => setSdkReady(true));
  }, []);
  return !sdkReady ? <div > loading...</div > : (
    <div>
      <LayoutRouter />
    </div>
  )
}
function Home(props) {
  const history = useHistory()
  let jxstate = null
  // let jxstate ={
  //   "battery_status":85,
  //   "weight_unit":2,
  //   "weight":63.3689,
  //   "body_r_enc":45623.36,
  //   "stable_data_flag":1
  // }
  if (history.location.state != null) {
    jxstate = history.location.state || null
    console.error("----------")
    console.error(jxstate)
  }
  // useDeviceData包含以下值，deviceData，deviceStatus，templateMap，templateList
  const [state, { onDeviceDataChange, onDeviceStatusChange }] = useDeviceData(sdk);
  const wulist = state.templateMap.weight_unit.define.mapping
  // 身体数据
  const [bodyInfo, setbodyInfo] = useState(null);
  // 从云端获取到的属性枚举值
  const unitindex = state.deviceData.weight_unit
  // WebSocket 监听
  useEffect(() => {
    // 监听设备控制推送
    const handleWsControl = ({ deviceId, deviceData }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceDataChange(deviceData);
      }
      console.log('Jkcard wsControl', deviceData);
    };
    // 监听设备上报数据推送
    const handleWsReport = ({ deviceId, deviceData }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceDataChange(deviceData);
      }
      console.log('Jkcard wsReport', deviceId, deviceData);
    };
    // 监听设备在线状态变更推送
    const handleWsStatusChange = ({ deviceId, deviceStatus }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceStatusChange(deviceStatus);
      }
      console.log('Jkcard wsStatusChange', deviceId, deviceStatus);
    };

    sdk
      .on('wsControl', handleWsControl)
      .on('wsReport', handleWsReport)
      .on('wsStatusChange', handleWsStatusChange);

    return () => {
      sdk
        .off('wsControl', handleWsControl)
        .off('wsReport', handleWsReport)
        .off('wsStatusChange', handleWsStatusChange);
    };
  }, []);
  // 检查固件更新
  useEffect(() => {
    // 检查固件更新，若有可升级固件，且设备在线，则弹出提示
    const doCheckFirmwareUpgrade = async () => {
      try {
        const upgradeInfo = await sdk.checkFirmwareUpgrade({
          silent: true, // 设置为 true 则只检查，不弹出提示
        }).then(({ CurrentVersion, DstVersion }) => {
          if (DstVersion && CurrentVersion !== DstVersion) {
            // 开发者需要在此处实现自定义的固件升级提示的展示
            Toast.info('发现新的固件版本，请手动升级！', 2)
          }
          sdk.blueToothAdapter.reportDeviceInfo(
            {
              productId: sdk.productId,
              deviceName: sdk.deviceName,
              deviceInfo: {
                // "module_hardinfo": "模组具体硬件型号 N10",
                "module_softinfo": CurrentVersion,
              }
            }
          )
        });
        console.log('firmware upgrade info', upgradeInfo);
      } catch (err) {
        console.error('checkFirmwareUpgrade fail', err);
      }
    };
    doCheckFirmwareUpgrade();


  }, []);
  // 首次加载获取数据
  useMemo(() => {
    // 首次加载读取，若无数据自动录入数据库
    getLastUserData()
    PubSub.subscribe('third_user', (msg, pubsubTest) => {
      // getThirdUserInfo(pubsubTest.id)
      getThirdUserInfo(pubsubTest.id).then(function onFulfilled(value) {
        if (value.height == null || value.birthday == null || value.height == "" || value.birthday == "") {
          // 用户信息为空,props.
          Toast.fail('用户信息不完整，无法计算体脂！请先录入数据！', 3)
          jxstate = {
            body_r_enc: 0,
            weight: 60,
            weight_unit: 0,
            stable_data_flag: 1
          }
          // history.push("/InputUserPage")
        }
      }).catch(function onRejected(error) {
        console.log('错误：' + error);
      });
      PubSub.unsubscribe("third_user");
    })
  }, [])
  useEffect(() => {
    async function fetchData() {
      // 获取最后一条数据
      await getThirdUserData()
    }
    fetchData();
    PubSub.subscribe('lastuserData', (msg, pubsubTest) => {
      if (Object.keys(pubsubTest).length != 0) {
        console.log("获取最后一条数据:", pubsubTest)
        setbodyInfo(pubsubTest)
      }
      PubSub.unsubscribe("lastuserData");//取消订阅
    })
  }, [jxstate])
  const showDeviceDetail = () => {
    history.location.state = null
    jxstate = null
    console.error(jxstate)
    console.error(history.location.state)
    // history.replace("/DeviceDetail")
    sdk.goDeviceDetailPage()
  }
  const showP = () => {
    console.log("showP")
    history.replace('/PanelPage')
  }
  return (
    <div className="device-panel clear-margin" style={{ minHeight: `${windowHeight}px` }}>
      <div>
        <div className="fl-rr">
          {/* <DeviceDetailBtn /> */}
          <RawBtn
            className="panel-more-btn"
            onClick={showDeviceDetail}
          >
            <div className="more-btn-icon" />
          </RawBtn>
        </div>
        <div className="jkcardpage">
          {/* <div className="floatbtn" onClick={showzl}>
          <img src={IMGURL+"home_btn_contact_n@3x.png"}/>
          </div> */}
          <div className="jkcon">
            {/* 健康card */}
            <div className="jkcard mgb">
              <div className="fl-cc wcolor">
                <div className="fl-rc weightinfo textcolor">
                  {bodyInfo == undefined ? "暂无数据！" : <WieghtCard weight={bodyInfo.weight} weight_u={bodyInfo.weight_u} wulist={wulist} />}
                </div>
                <div className="fl-rc tipstext">
                  <img src={IMGURL + "site.png"} />
                </div>
                <div className="fl-rc" onClick={showP} >
                  <span className="lfbtn"><img src={IMGURL + "btn_cz.png"} />测量</span>
                </div>
              </div>
            </div>
          </div>
          {/* 测量数据 */}
          <div className="textcolor mgb fl-rsbc">
            <div className="tittext">测量数据</div>
            <div className="ttext"><Link to={{ pathname: '/CklsPage', state: { pagename: 'chakan', unit: unitindex } }} className="textcolor" replace> 查看历史</Link></div>
          </div>
          {bodyInfo == undefined ? <div className="textcolor mgtb">暂无数据，请连接体脂秤！</div> :
            <>
              <div className="cssj mgb">
                {bodyInfo == undefined ? "暂无数据！" : <BiminfoCard BMI={parseFloat(bodyInfo.BMI).toFixed(1)} BMI_u={bodyInfo.BMI_u} />}
              </div>
              <div className="jkcardlist">
                {bodyInfo == undefined ? "暂无数据！" : <BodyInfoCard bodyInfo={bodyInfo} />}
              </div>
            </>
          }
          {/* 数据对比 */}
          <div className="textcolor mgb fl-c">
            <div className="tittext">数据对比</div>
            <div className="ttext mgt5">选择您的两次测量数据，对其变化进行比对</div>
          </div>
          <div className="bd1 sjdbimg pdb">
            <Link to={{ pathname: '/CklsPage', state: { pagename: 'duibi' } }} replace>
              <img src={IMGURL + "db.png"} />
            </Link>
          </div>
          <div className="pdtb tc gc fl-rc kfxx">
            <img src={IMGURL + "phone.png"} />客服电话: 400-6035-688
          </div>
        </div>
      </div>
      <Version />
    </div>
  );
}
// 测量处理数据页面
function PanelPage() {
  const history = useHistory()
  const isStandardBleDevice = sdk.isStandardBleDevice;
  const BleRef = useRef()
  useEffect(() => {
    console.log("bleRef.current",BleRef.current)
    let bleMessage = BleRef!=undefined && BleRef.current!=undefined ? BleRef.current.bleMessage : {}
    let bleData = BleRef!=undefined && BleRef.current!=undefined ? BleRef.current.bleData : ""
    console.error("bleMessage",bleMessage)
    // let bleMessage = {
    //   "battery_status": 30,
    //   "weight_unit": 0,
    //   "weight": 71.3,
    //   "body_r_enc": 4560,
    //   "stable_data_flag": 1 -bleMessage.weight > 0 &&
    // }
    // if (Object.keys(bleMessage).length > 0 && bleMessage.stable_data_flag == 1 && (bleMessage.weight != NaN && bleMessage.weight != null && bleMessage.weight_unit != null && bleMessage.weight_unit != NaN)) {
    //   console.error("bleMessage",bleMessage)
    //   addDevData(bleMessage,bleData)
    //   Toast.hide();
    //   BleRef.current.disconnectDevice()
    // }
  }, [BleRef.current])
  return (
    <div className="bluetooth-panel bdwhite" style={{ minHeight: `${windowHeight}px` }}>
      <div className="fl-cc">
        {isStandardBleDevice && (
          <StandardBleConnector familyId={sdk.familyId} deviceId={sdk.deviceId} ref={BleRef} />
        )}
      </div>
    </div>
  )
}
export function Bzbgcolor({ levelList, levelNum, levelRange }) {
  return (
    <span className={classNames("wstate", bdwstate(checkAdult(levelList, levelNum, levelRange)))}>
      {checkAdult(levelList, levelNum, levelRange)}
    </span>
  )
}
// 数据对比
export const checkAdult = (reslist, val, resrange) => {
  var resindex = 0
  if (reslist != undefined && reslist.length > 0) {
    reslist.map((item, i) => {
      if (val > item && val < reslist[i + 1]) {
        resindex = i
      }
    })
    // console.log(reslist + "---" + resrange[resindex])
    return resrange[resindex]
  } else {
    return "暂无"
  }
}
// 查找样式
export const bdwstate = (v) => {
  var levelStyle = "gr"
  switch (v) {
    case "不⾜": case "偏瘦": case "偏低": case "缺失": case "较轻": case "无": case "营养不良": case "轻度肥胖":
      levelStyle = "pt"
      break
    case "过轻": case "偏胖": case "偏胖型": case "轻度肥胖": case "中度营养不良": case "过重": case "警戒":
      levelStyle = "pg"
      break
    case "隐性胖": case "中度肥胖": case "营养过剩": case "偏瘦型": case "运动型偏胖": case "偏⾼": case "肥胖":
      levelStyle = "pt"
      break
    case "标准": case "健康": case "正常": case "偏瘦运动型": case "标准型":
      levelStyle = "bz"
      break
    case "优": case "标准运动型": case "运动健美型":
      levelStyle = "gg"
      break
    case "极度肥胖": case "重度肥胖": case "营养严重过剩": case "营养过剩": case "严重营养不良": case "缺乏锻炼型": case "严重偏⾼":
      levelStyle = "yz"
      break
  }
  return levelStyle
}
// weight组件
function WieghtCard({ weight, weight_u, wulist }) {
  console.log({ weight, weight_u, wulist })
  weight_u = weight_u == null || weight_u == "" ? 0 : weight_u
  // 根据单位显示体重
  const [iweight, setiweight] = useState("0.00")
  const [iweight_unit, setiweight_unit] = useState("KG")
  useEffect(() => {
    let weightData = forunit(weight, weight_u)
    console.log(weightData)
    if (weightData != undefined) {
      console.log(weightData)
      setiweight(weightData.weight)
      setiweight_unit(wulist[weight_u])
    }
  }, [])
  return (
    <div className="weight fl-cc">
      {/* 处理后的单位和体重 */}
      <div className="wnum mgb">
        {iweight}<span className="ttext">{iweight_unit}</span>
      </div>
      <div className="tittext">体重：
        <span className="gc">{weight_u != null ? resweightRange[weight_u] : "标准"}</span>
      </div>
    </div>
  )
}
// bimcard组件
function BiminfoCard({ BMI, BMI_u }) {
  let biminfo = {
    name: "BMI", num: BMI, level: BMI_u, levelStand: [0,18.5, 24, 30]
  }
  return (
    <div className="cssjcard psbgcolor wcolor pd fl-rsbc">
      <div className="fl-cc cssjtit">
        <div>{biminfo.name}</div>
        <div>{biminfo.num}</div>
      </div>
      <div className="cssjrcon">
        <div className="tr mgb"><span className="bzstate">{checkAdult(listbmiWHORange, biminfo.num, resbmiWHORange)}</span></div>
        <div className="prog tsize">
          <Bimlevel iStand={biminfo.levelStand} num={biminfo.num} level={biminfo.level} />
        </div>
      </div>
    </div>
  )
}
function Bimlevel(props) {
  const levellist = resbmiWHORange
  let iStand = props.iStand
  let num = props.num
  let level = levellist.indexOf(props.level)
  // let level = 0      // 数组去重
  function unique(arr) {
    return Array.from(new Set(arr))
  }
  useMemo(() => {
    if (iStand.length > 0) {
      iStand.unshift(0)
    }
    iStand = unique(iStand)
  }, [])
  return (
    <>
      {iStand.length == 0 ? "暂无数据！" :
        <div>
          <div className="prog-tit" style={{"gridTemplateColumns":"repeat("+levellist.length+", 1fr)"}}>
            {levellist.map((item, index) => { return <span key={index}>{item}</span> })}
          </div>

          <div className="prog-bar mgtb" style={{"gridTemplateColumns":"repeat("+iStand.length+", 1fr)"}}>
            {iStand.map(function (item, index) { return <span key={index} className={classNames('bdwhite',{ "selected": item <= num }, { "lastchild": level == index })}></span> })}
          </div>
          <div className="prog-desc" style={{"gridTemplateColumns":"repeat("+iStand.length+", 1fr)"}}>
            {iStand.map(function (item, index) { return <span key={index}>{item}</span> })}
          </div>
        </div>
      }
    </>
  )
}
// 体脂数据card组件
function BodyInfoCard({ bodyInfo }) {
  // 重组数据
  let listArry = [
    { num: bodyInfo.fatRate, name: "脂肪率", unit: "(%)", levelNum: bodyInfo.fatRate_u, levelList:listFatRange, levelRange:resFatRange},
    { num: bodyInfo.fatKg, name: "脂肪量", unit: "", levelNum: bodyInfo.fatKg_u , levelList:listFatRange1, levelRange:resFatRange1},
    { num: bodyInfo.muscleRate, name: "肌肉率", unit: "(%)", levelNum: bodyInfo.muscleRate_u , levelList:listMuscleRange, levelRange:resMuscleRange},
    { num: bodyInfo.muscleKg, name: "肌肉量", unit: "", levelNum: bodyInfo.muscleKg_u , levelList:listMuscleKg, levelRange:resMuscleKg},
    { num: bodyInfo.waterRate, name: "水分", unit: "", levelNum: bodyInfo.waterRate_u , levelList:listWaterRange, levelRange:resWaterRange},
    { num: bodyInfo.visceralFat, name: "内脏脂肪", unit: "", levelNum: bodyInfo.visceralFat_u , levelList:listFatRange, levelRange:resFatRange},
    { num: bodyInfo.visceralFatKg, name: "内脏脂肪量", unit: "", levelNum: bodyInfo.visceralFatKg_u , levelList:listFatRange, levelRange:resFatRange},
    { num: bodyInfo.boneRate, name: "骨率", unit: "(%)", levelNum: bodyInfo.boneRate_u , levelList:listBoneRange, levelRange:resBoneRange},
    { num: bodyInfo.boneKg, name: "骨量", unit: "", levelNum: bodyInfo.boneKg_u , levelList:listBoneRange, levelRange:resBoneRange},
    { num: bodyInfo.BMR, name: "基础代谢", unit: "", levelNum: bodyInfo.BMR_u , levelList:listbmrRange, levelRange:resbmrRange},
    { num: bodyInfo.proteinPercentageKg, name: "蛋白质", unit: "", levelNum: bodyInfo.proteinPercentageKg_u , levelList:listNutrition, levelRange:resNutrition},
    { num: bodyInfo.bodyAge, name: "身体年龄", unit: "", levelNum: bodyInfo.bodyAge_u, levelList:[0,50], levelRange:resageRange },
    { num: bodyInfo.notFatWeight, name: "去脂体重", unit: "KG", levelNum: bodyInfo.notFatWeight_u , levelList:listbodyShape, levelRange:resbodyShape},
    { num: bodyInfo.obesityLevel, name: "肥胖等级", unit: "", levelNum: bodyInfo.obesityLevel_u , levelList:listobesity, levelRange:resobesity},
    { num: bodyInfo.fatRate, name: "脂肪率", unit: "(%)", levelNum: bodyInfo.fatRate_u , levelList:listFatRange, levelRange:resFatRange},
  ]
  return (
    listArry.map((item, index) => {
      return (
        <div className="jkinfocard mgb textcolor fl-cc pd" key={index}>
          <div className="numtext">{parseFloat(item.num).toFixed(2)}</div>
          <div className="ttext mgtb">{item.name + " " + item.unit}</div>
          <div className={classNames({ 'displyn': item.levelNum == "" })}>
            {item.levelNum != "" && 
              <Bzbgcolor levelList={item.levelList} levelNum={item.levelNum} levelRange={item.levelRange}/>
            }
          </div>
        </div>
      )
    })
  )
}
// 添加体脂数据
const addThirdUserData = (bdinfo) => {
  var request = require('superAgent')
  bdinfo.productId = sdk.productId,
    bdinfo.deviceName = sdk.deviceName,
    bdinfo.wx_unionid = myuserInfo.UserID
  bdinfo.impedance = "0",
    bdinfo.c_time = (moment(current_time).valueOf()),
    // bdinfo.user_height=userinfo.height,
    // bdinfo.user_weight=parseFloat(jxstate.weight).toFixed(2),
    // bdinfo.user_weight_u=parseInt(jxstate.weight_unit),
    console.log("addThirdUserData-bdinfo", bdinfo)
  request
    .post(APIURL + 'addThirdUserData')
    .send(bdinfo)
    .end(function (err, res) {
      console.log("addThirdUserData-res", res)
      if (res.body.code == 1) {
        Toast.success("更新成功！")
      } else {
        console.log('服务器出错' + res)
        Toast.fail(res.body.msg)
      }
    })
}
// 获取最新的用户基本信息
const getLastUserData = () => {
  var request = require('superAgent')
  request
    .post(APIURL + 'getlastuserinfo_tx')
    .send({
      "productId": sdk.productId,
      "deviceName": sdk.deviceName,
      "wx_unionid": myuserInfo.UserID,
      "username": myuserInfo.NickName,
      "userimg": myuserInfo.Avatar,
    })
    // .set('Content-Type', 'application/text')
    .end(function (err, res) {
      if (res.body.code == 1) {
        var JkcardUdata = res.body.data.third_user
        console.log('获取最新的用户数据', JkcardUdata)
        PubSub.publish('third_user', JkcardUdata)
      } else {
        console.log('服务器' + res)
      }
    })
}
// 存储的历史用户数据
const getThirdUserData = async () => {
  var request = require('superAgent')
  request
    .post(APIURL + 'getThirdUserData_structure')
    .send({
      "productId": sdk.productId,
      "deviceName": sdk.deviceName,
      "thirdUserNo": thirdUserNo,
      "wx_unionid": myuserInfo.UserID,
      "pageNo": 1,
      "pageSize": 10,
    })
    .end(function (err, res) {
      console.log("历史用户数据:", res)
      if (res.body.code == 1) {
        var JkcardUdata = res.body.data.data.reverse()
        console.log("历史用户数据排序后:", JkcardUdata)
        if (JkcardUdata.length > 0) {
          PubSub.publish('lastuserData', ((JkcardUdata[0].user_data).reverse())[0])
        }
      } else {
        console.log('服务器' + err)
      }
    })
}
// 实时计算出体脂数据
function getbdinfo(userinfo, hexString) {
  console.log("最后一次数据-userinfo")
  console.log(userinfo,hexString)
  var age = matAge(parseInt(userinfo.birthday), parseInt(current_time))
  var request = require('superAgent')
  request
    .post("https://lx.yodatech.cn/app/user/body/params")
    .send({
      "age": age,
      "appid": APPID,
      "height": parseFloat(userinfo.height),
      "hexString": '5C'+hexString,
      "nonce": randomNum(1, 2048).toString(),
      "scaleType": 1,//体脂秤类型 1：四极秤 2：八极秤, 默认：1 四极秤
      "sex": parseInt(userinfo.sex),
      "signature": signature(),
      "timeStamp": new Date().valueOf()
    })
    .end(function (err, res) {
      console.log("最后一次数据")
      console.log(res)
      if (res.statusCode == 200) {
        var result = res.body
        console.log(result)
        if (result.code == 1000) {
          let bdinfo = result.data
          console.log("计算出体脂数据")
          console.log(bdinfo)
          if (bdinfo != null) {
            PubSub.publish('xhData', bdinfo)
          }
          else {
            Toast.fail("获取信息失败，请确保您已录入体重、身高、年龄！")
          }
        }
      }
      else {
        console.log('服务器出错' + res)
      }
    })
}
// 通过ID获取三方用户数据
const getThirdUserInfo = (id) => {
  return new Promise(function (resolve, reject) {
    var request = require('superAgent')
    request
      .post(APIURL + 'getThirdUserInfo')
      .send({
        "productId": sdk.productId,
        "deviceName": sdk.deviceName,
        "thirdUserId": id,
        "wx_unionid": myuserInfo.UserID,
      })
      .end(function (err, res) {
        if (res.body.code == 1) {
          var userinfo = res.body.data.third_user
          console.log('获取三方用户数据如下：')
          console.log(userinfo)
          resolve(userinfo);
        } else {
          console.log('服务器出错' + res)
          reject(new Error(res.body));
        }
      })
  });
}
// 签名
const signature = () => {
  // let md5 = require('js-md5');
  let tme = new Date().valueOf().toString();
  let nonce = randomNum(1, 1024).toString()
  // let tempSIGA = (md5("nonce="+nonce+"timeStamp="+tme+""+APPSECRET)).toUpperCase()
  let tempSIGA = md5("nonce=" + 1903 + "timeStamp=" + 1648804109989 + "" + APPSECRET).toUpperCase()
  console.log("需要签名字符串：", "nonce=" + nonce + "timeStamp=" + tme + "" + APPSECRET)
  console.log("签名:", tempSIGA)
  console.log("签名类型:", typeof (tempSIGA))
  console.log("签名:", md5("nonce=" + 1903 + "timeStamp=" + 1648804109989 + "" + APPSECRET).toUpperCase())
  return tempSIGA
}
//生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10);
      break;
    case 2:
      return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
      break;
    default:
      return 0;
      break;
  }
}
export const addDevData = async (bleMessage,bleData) => {
  console.log("添加addDevData",bleMessage,bleData)
  Toast.loading('正在获取数据，请稍等...');
  let third_user = {}
  PubSub.subscribe('third_user', (msg, pubsubTest) => {
    third_user = pubsubTest
    if (third_user.height == null || third_user.birthday == null || third_user.height == "" || third_user.birthday == "") {
      third_user.height = 160
      third_user.birthday = current_time
    }
    getbdinfo(third_user, bleData)
    PubSub.unsubscribe("third_user");
  })
  // 存储体脂数据
  PubSub.subscribe('xhData', (msg, pubsubTest) => {
    console.error("要添加的数据：", pubsubTest)
    if (Object.keys(pubsubTest).length != 0) {
      pubsubTest.weight_u = bleMessage.weight_unit
      addThirdUserData(pubsubTest)
    }
    //取消订阅
    PubSub.unsubscribe("lefuData");
  })
}